package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;

/**
 * 动态长度
 * 
 * @author shenliuyang
 *
 *         2016年8月1日上午10:49:17
 */
public class DynamicByteArrayFieldReaderWriter extends FieldReaderWriter {

	public DynamicByteArrayFieldReaderWriter(Field field, int size, int order) {
		super(field, size, order);
	}

	@Override
	public void read(InputStream in, Object to) throws IOException {
		byte[] length = new byte[size];
		in.read(length);
		int head = 0;
		for (int i = 0; i < size; i++) {
			head <<= 8;
			head |= length[i] & 0xFF;
		}
		byte[] data = new byte[head];
		in.read(data);
		wrtietoField(to, data);
	}

	@Override
	public void write(OutputStream out, Object from) throws IOException {
		byte[] data = (byte[]) readFromField(from);
		if (data == null) {
			data = new byte[0];
		}
		if (size == 1) {
			out.write((byte) data.length);
		} else if (size == 2) {
			ByteBuffer bb = ByteBuffer.allocate(2);
			bb.putShort((short) data.length);
			out.write(bb.array());
		} else if (size == 4) {
			ByteBuffer bb = ByteBuffer.allocate(4);
			bb.putInt(data.length);
			out.write(bb.array());
		}
		out.write(data);
	}
}